<template>
  <div>
    <el-dialog title="修改密码" :visible.sync="visible" v-if="visible">
      <el-form ref="formInfo" :model="formInfo" :rules="rules" label-position="right" label-width="80px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input show-password v-model="formInfo.oldPassword" placeholder="原密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input show-password v-model="formInfo.password" placeholder="新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input show-password v-model="formInfo.confirmPassword" placeholder="确认密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="updatePassword">提交</el-button>
        <el-button type="warning" @click="visible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const formInfo = {
  oldPassword: '',
  password: '',
  confirmPassword: ''
}
export default {
  name: 'UpdatePassword',
  data () {
    return {
      visible: false,
      formInfo: { ...formInfo },
      rules: {
        oldPassword: [{
          required: true,
          message: '原密码不能为空',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '新密码不能为空',
          trigger: 'blur'
        }],
        confirmPassword: [{
          required: true,
          message: '确认密码不能为空',
          trigger: 'blur'
        }, {
          validator: (rule, value, callback) => {
            if (value === this.formInfo.password) {
              callback()
            } else {
              callback(new Error('两次密码不一致'))
            }
          },
          trigger: 'blur'
        }]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.formInfo = { ...formInfo }
    },
    updatePassword () {
      this.$refs.formInfo.validate(valid => {
        if (valid) {
          this.$http.post('admin/user/password', this.formInfo).then(() => {
            this.$alert('更新密码成功，请重新登录！', { type: 'success' }).then(() => {
              this.visible = false
              this.$emit('onCloseDialog')
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
